package swd.function;

import java.io.*;
import java.util.*;

import com.pub.database.*;
import com.pub.tools.*;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 * @deprecated
 */
public class SwdFunction {


    public QueryBean gqbnDAO = null;


    public SwdFunction(QueryBean pqbnDAO) {
        gqbnDAO = pqbnDAO;
    }

    /**
     * getDbfNO
     *
     * @param pstrPrgNO String
     * @param pstrFrmNO String
     * @return string
     */
    public String getDbfNO(String pstrPrgNO, String pstrFrmNO) {
        String lstrDbfNO = null;

        try {
            lstrDbfNO = ((ArrayList<Object>) gqbnDAO.querySQL(
                    "select dbf_no from wkf_frm0 where prg_no='" + pstrPrgNO +
                    "' and frm_no='" + pstrFrmNO + "'").get(0)).get(0).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return lstrDbfNO;
    }

    /**
     * getFldKind
     *
     * @param pstrDbfNO String
     * @param pstrFldNO String
     * @return String
     */
    public String getFldKind(String pstrDbfNO, String pstrFldNO) {
        String lstrFldKind = null;

        try {
            lstrFldKind = ((ArrayList<Object>) gqbnDAO.querySQL(
                    "select fld_kind from wkf_layout where dbf_no='" +
                    pstrDbfNO + "' and fld_no='" + pstrFldNO + "'").get(0)).get(
                            0).toString();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        return lstrFldKind;
    }

    /**
     * getFldKind
     *
     * @param pstrPrgNO String
     * @param pstrFrmNO String
     * @param pstrSeqno String
     * @return String
     */
    public String getFldKind(String pstrPrgNO, String pstrFrmNO,
                             String pstrSeqno) {
        String lstrFldKind = null;

        try {
            lstrFldKind = ((ArrayList<Object>) gqbnDAO.querySQL(
                    "select fld_kind from wkf_layout where dbf_no='" +
                    getDbfNO(pstrPrgNO, pstrFrmNO) + "' and fld_no='" +
                    getFldNO(pstrPrgNO, pstrFrmNO, pstrSeqno) + "'").get(0)).
                          get(0).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return lstrFldKind;
    }

    /**
     * getFldNO
     *
     * @param pstrPrgNO String
     * @param pstrFrmNO String
     * @param pstrSeqno String
     * @return String
     */
    public String getFldNO(String pstrPrgNO, String pstrFrmNO, String pstrSeqno) {
        String lstrFldNO = null;
        try {
            lstrFldNO = ((ArrayList<Object>) gqbnDAO.querySQL(
                    "selet fld_no from wkf_frm1 where prg_no='" + pstrPrgNO +
                    "' and frm_no='" + pstrFrmNO + "' and seqno='" + pstrSeqno +
                    "'").get(0)).get(0).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return lstrFldNO;
    }

    /**
     * getFwrPrgNO
     *
     * @param pstrBeanFileName String
     * @param pstrUserNO String
     * @param pstrPrgNO String
     * @return BufferedWriter
     */
    public BufferedWriter getFwrPrgNO(String pstrBeanFileName,
                                      String pstrOutPath, String pstrUserNO,
                                      String pstrPrgNO) {

        //String lstrOutPath = null;
        BufferedWriter lbwrPrgNO = null;

        try {
            //lstrOutPath = getPrgOutputPath(pstrUserNO, pstrPrgNO);

            /*if (lstrOutPath.equals("fail")) {
                throw new Exception("get output path fail!!");
                         }*/

            if (!(new File(pstrOutPath)).isDirectory()) {
                new File(pstrOutPath).mkdirs();
            }

            //false代表覆蓋
            lbwrPrgNO = new BufferedWriter(new FileWriter(pstrOutPath + "\\" +
                    pstrBeanFileName, false));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return lbwrPrgNO;
    }

    /**
     * getPrgOutputPath
     *
     * @param pstrUserNO String
     * @param pstrPrgNO String
     * @return String
     */
    public String getPrgOutputPath(String pstrUserNO, String pstrPrgNO) {
        Hashtable<String,Object> lhtWKF_INI_FILE = null;
        String lstrOutPath = null;

        try {
            lhtWKF_INI_FILE = (Hashtable<String,Object>) gqbnDAO.hashtableSQL("select jsp_frame_path,apserver_url,apserver_port,sys_no from wkf_ini_file where user_no='" +
                    pstrUserNO + "'").get("0");

            //讀取程式輸出的路徑
            lstrOutPath = tran_path(pstrUserNO,
                                    lhtWKF_INI_FILE.get(
                                            "JSP_FRAME_PATH").
                                    toString(),
                                    lhtWKF_INI_FILE.get("APSERVER_URL").
                                    toString(),
                                    lhtWKF_INI_FILE.get("APSERVER_PORT").
                                    toString(),
                                    lhtWKF_INI_FILE.get("SYS_NO").
                                    toString());

            if (lstrOutPath.indexOf("successfull") == 0) {
                lstrOutPath = PublicFunction.getDesSplitString(lstrOutPath, "/",
                        1);
                lstrOutPath = (new StringBuffer(lstrOutPath)).append(
                        "com\\swd\\").
                              append(lhtWKF_INI_FILE.get("SYS_NO").toString()).
                              append("\\").append(pstrPrgNO).
                              toString();
            } else if (lstrOutPath.indexOf("fail") == 0) {
                lstrOutPath = "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lstrOutPath;
    }

    /**
     * getSimpBeginnerVarType
     *
     * @param pstrVaribleType String
     *
     * @return String
     */
    public String getSimpBeginnerVarType(String pstrVaribleType) {
        if (pstrVaribleType.toLowerCase().equals("int")) {
            return "int";
        } else if (pstrVaribleType.toLowerCase().equals("long")) {
            return "lng";
        } else if (pstrVaribleType.toLowerCase().equals("double")) {
            return "dbl";
        } else if (pstrVaribleType.toLowerCase().equals("float")) {
            return "flt";
        } else if (pstrVaribleType.toLowerCase().equals("char")) {
            return "chr";
        } else if (pstrVaribleType.toLowerCase().equals("string")) {
            return "str";
        }
        return "str";
    }

    /**
     * getSysNO
     *
     * @param pstrUserNO String
     * @return String
     */
    public String getSysNO(String pstrUserNO) {
        return ((ArrayList<Object>) gqbnDAO.querySQL(
                "select sys_no from wkf_ini_file where user_no='" +
                pstrUserNO + "'").get(0)).get(0).toString();
    }

    public String[] get_color_set(String pstrPrgNO) {
        String lstrColor[] = new String[3];
        String lstrColorSet = new String();
        try {
            lstrColorSet = ((ArrayList<Object>) gqbnDAO.querySQL(
                    "select color_set from wkf_frm0 where prg_no='" + pstrPrgNO +
                    "' and seqno='0001' order by prg_no,seqno").get(0)).get(0).
                           toString();

            switch (Integer.parseInt(lstrColorSet)) {
            case 0:
                lstrColor[0] = "table_head";
                lstrColor[1] = "td_head";
                lstrColor[2] = "td_content";
                break;
            case 1:
                lstrColor[0] = "head_green";
                lstrColor[1] = "content_green";
                lstrColor[2] = "content_green_white";
                break;
            case 2:
                lstrColor[0] = "head_orange";
                lstrColor[1] = "content_orange";
                lstrColor[2] = "content_orange_white";
                break;
            case 3:
                lstrColor[0] = "head_purple";
                lstrColor[1] = "content_purple";
                lstrColor[2] = "content_purple_white";
                break;
            default:
                lstrColor[0] = "table_head";
                lstrColor[1] = "td_head";
                lstrColor[2] = "td_content";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return lstrColor;
    }

    public String get_edit_mode_css(String pstrRwMode, String pstrFldKind,
                                    String pstrOpenDB, String pstrGetFld,
                                    String pstrReadonlyYN, String pstrDDNO,
                                    String pstrLinkKind) {
        String lstrEditMode = null;
        String lstrCss = null;

        try {
            if (pstrRwMode.equals("H")) { //Hidden
                lstrEditMode = "HIDDEN";
                lstrCss = "input";
            }

            if (pstrRwMode.equals("F")) {
                lstrEditMode = "FILE";
                lstrCss = "input";
            }

            if (pstrRwMode.equals("T")) {
                lstrEditMode = "TEXT";
                lstrCss = ((pstrGetFld != null && !pstrGetFld.equals("")) ||
                           (pstrOpenDB != null &&
                            (pstrOpenDB.equals("DATE") ||
                             pstrOpenDB.equals("DATETIME"))) ?
                           "input_window hand" : "input");
            }

            if (pstrRwMode.equals("B")) {
                lstrEditMode = "BUTTON";
                lstrCss = "button b_normal";
            }

            if (pstrRwMode.equals("C")) {
                lstrEditMode = "CHECKBOX";
                lstrCss = "checkbox";
            }

            if (pstrRwMode.equals("R")) {
                lstrEditMode = "RADIO";
                lstrCss = "radio";
            }

            if (pstrRwMode.equals("L")) {
                lstrEditMode = "LINK";
                lstrCss = "input_a";
            }

            if (pstrRwMode.equals("E")) {
                lstrEditMode = "RESET";
                lstrCss = "button";
            }

            if (pstrRwMode.equals("S")) {
                lstrEditMode = "SUBMIT";
                lstrCss = "button";
            }

            if (pstrRwMode.equals("A")) {
                lstrEditMode = "NOTELINE";
                lstrCss = "text_head";
            }

            if (pstrRwMode.equals("D")) {
                lstrEditMode = "SELECT";
                lstrCss = "select";
            }

            if (pstrRwMode.equals("M")) {
                lstrEditMode = "TEXTAREA";
                lstrCss = "textarea";
            }

            if (pstrRwMode.equals("N")) {
                lstrEditMode = "RICHTEXT";
                lstrCss = "textarea";
            }

            if (pstrRwMode.equals("V")) {
                lstrEditMode = "TEXT";
                lstrCss = "input_noborder";
            }

            if (pstrReadonlyYN.equals("Y")) {
                lstrCss = (pstrLinkKind.equals("B") ? "input_lock" :
                           "input_noborder");
                if (pstrRwMode.equals("M") || pstrRwMode.equals("N")) {
                    lstrCss = "textarea_noborder";
                }
            }

            if (pstrFldKind.endsWith("N")) {
                lstrCss = (new StringBuffer(lstrCss)).append(" num").toString();
            }

            return (new StringBuffer("success")).append("/").append(
                    lstrEditMode).append(",").append(lstrCss).toString();
        } catch (Exception e) {
            return (new StringBuffer("fail")).append("/").append(e.toString()).
                    toString();
        }
    }

    public String get_wkf_ini_file_data(String pstrUserNO, String pstrFldNO,
                                        String pstrServer, String pstrPortNO,
                                        String pstrSysNO) {
        Hashtable<String,Object> lhtEnvData = null;
        Hashtable<String,Object> lhtDBData = null;
        StringBuffer lstbSQL = new StringBuffer();
        String lstrRtn = new String();

        try {
            lstbSQL.append("select * from wkf_ini_file where user_no='");
            lstbSQL.append(pstrUserNO);
            lstbSQL.append("'");

            lhtEnvData = gqbnDAO.readSingleRowData(lstbSQL.toString());

            if (lhtEnvData == null) {
                return (new StringBuffer()).append("fail/no have user ").append(
                        pstrUserNO).append(" enviroment data in wkf_ini_file").
                        toString();
            }

            pstrServer = (pstrServer == null || pstrServer.trim().equals("") ?
                          lhtEnvData.get("APSERVER_URL").toString() :
                          pstrServer);
            pstrPortNO = (pstrPortNO == null || pstrPortNO.trim().equals("") ?
                          lhtEnvData.get("APSERVER_PORT").toString() :
                          pstrPortNO);
            pstrSysNO = (pstrSysNO == null || pstrSysNO.trim().equals("") ?
                         lhtEnvData.get("SYS_NO").toString() : pstrSysNO);

            if (pstrFldNO.trim().equals("PAGE_SIZE")) {
                lstrRtn = lhtEnvData.get(pstrFldNO.toUpperCase()).toString();
            } else if (pstrFldNO.trim().equals("DB_KIND") ||
                       pstrFldNO.trim().equals("FLD_SET_NO") ||
                       pstrFldNO.trim().equals("LOOKUP_NAME")) {
                lstbSQL.delete(0, lstbSQL.length());
                lstbSQL.append("select ");
                lstbSQL.append(pstrFldNO);
                lstbSQL.append(" from wkf_db_file where dbf_no='");
                lstbSQL.append(lhtEnvData.get("DB_CONNECT_SET"));
                lstbSQL.append("'");

                lhtDBData = gqbnDAO.readSingleRowData(lstbSQL.toString());

                if (lhtDBData != null) {
                    lstrRtn = lhtDBData.get(pstrFldNO.
                            toUpperCase()).toString();
                }
            } else {
                lstrRtn = lhtEnvData.get(pstrFldNO.toUpperCase()).toString();
            }

            lstrRtn = tran_path(pstrUserNO, lstrRtn, pstrServer, pstrPortNO,
                                pstrSysNO);
            if (lstrRtn.indexOf("successfull") == 0) {
                lstrRtn = PublicFunction.getDesSplitString(lstrRtn, "/", 1);
            } else if (lstrRtn.indexOf("fail") == 0) {
                return (new StringBuffer(lstrRtn)).append("/").append(
                        "createPage").toString();
            }

            return (new StringBuffer("successfull")).append("/").append(lstrRtn).
                    toString();
        } catch (Exception e) {
            return (new StringBuffer("fail")).append("/").append(e.toString()).
                    append("/").append("get_wkf_ini_file_data").toString();
        } finally {

        }
    }

    /**
     *
     * @param pbwrPrgNO BufferedWriter 輸出物件
     * @param pstrSysNO String 系統編號
     * @param pstrPrgNO String 程式編號
     * @param pstrBeanName String 要產生的JavaBean 名稱
     * @param pstbTabStr StingBuffer 縮排字集
     * @param pstrTabChar String 縮排字元
     * @return String
     */
    public String outputBeanHeader(BufferedWriter pbwrPrgNO, String pstrSysNO,
                                   String pstrPrgNO, String pstrBeanName,
                                   StringBuffer pstbTabStr, String pstrTabChar) {
        try {
            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "package com.swd." + pstrSysNO + "." + pstrPrgNO +
                           ";", 0);

            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "import com.pub.database.*;", 2);
            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "import java.util.*;", 1);
            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "import javax.servlet.http.*;", 1);
            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "import floweng.*;", 1);
            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "import com.pub.tools.PropertyBean;", 1);

            outputJavaCode(pbwrPrgNO, pstbTabStr, pstrTabChar,
                           "public class " +
                           pstrBeanName.substring(0, pstrBeanName.indexOf(".")) +
                           " {", 2);

            return "successfull";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        } finally {

        }
    }

    /**
     * outputJavaCode
     *
     * @param pbwrOutput BufferedWriter 輸出物件
     * @param pstbTabString StringBuffer 縮排字串
     * @param pstrTabChar String 組成組排字串的字元
     * @param pstrJavaCode String 要輸出的Java code
     * @param pintNewLine integer 輸出所需的換行數
     */
    public void outputJavaCode(BufferedWriter pbwrOutput,
                               StringBuffer pstbTabString, String pstrTabChar,
                               String pstrJavaCode, int pintNewLineCount) {
        try {
            for (int i = 1; i <= pintNewLineCount; i++) {
                pbwrOutput.newLine();
            }

            int lintBeginSingleCnt = PublicFunction.getDesStrCount(pstrJavaCode,
                    "{");
            int lintEndSingleCnt = PublicFunction.getDesStrCount(pstrJavaCode,
                    "}");

            if (pstbTabString != null && (lintBeginSingleCnt < lintEndSingleCnt)) { //判斷是否凸排
                pstbTabString.delete(0, pstrTabChar.length());
            }

            if (pstbTabString != null) {
                pbwrOutput.write(pstbTabString.toString()); //先輸出縮排字串
            }

            pbwrOutput.write(pstrJavaCode); //輸出Java code

            if (lintBeginSingleCnt > lintEndSingleCnt) { //判斷是否凹排
                pstbTabString.append(pstrTabChar);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用來輸出含縮排的Tag
     * @param pbwrOutput BufferedWriter 輸出物件
     * @param pstbTabString StringBuffer 前置 Tab String
     * @param pstrTabCharecter String 以何種字元當成 Tab
     * @param pstrTagText String 要輸出的 Tag
     * @param pblnNewLine boolean 是否要換行
     * @sample outputPageTag(pbwrPrgNO,StringBuffer("\t\t"),"\t","<BODY>",true) return "\t\t\t"<br>
               outputPageTag(pbwrPrgNO,StringBuffer("\t\t\t"),"\t","</BODY>",true) return "\t\t"<br>
               outputPageTag(pbwrPrgNO,StringBuffer("\t\t"),"\t","<OPTION>TEST</OPTION>",true) return "\t\t"<br>

     */
    public void outputPageTag(BufferedWriter pbwrOutput,
                              StringBuffer pstbTabString,
                              String pstrTabCharecter, String pstrTagText,
                              boolean pblnNewLine) {
        StringBuffer lstbOutputText = new StringBuffer(pstrTagText);
        try {
            //當輸出為tag 結束符號時，內縮次數減一次
            if (pstrTagText.indexOf("</") == 0) {
                pstbTabString.delete(0, pstrTabCharecter.length());
            }

            //輸出此Tag前是否需換行
            if (pblnNewLine) {
                pbwrOutput.newLine();
                lstbOutputText.insert(0, pstbTabString.toString());
            }

            pbwrOutput.write(lstbOutputText.toString());

            if (pstrTagText.indexOf("<") == 0 && pstrTagText.indexOf("</") < 0 &&
                pstrTagText.indexOf("<!") < 0 &&
                !(pstrTagText.indexOf("</") > 0 ||
                  pstrTagText.indexOf("/>") == pstrTagText.length() - 2)) {
                pstbTabString.append(pstrTabCharecter);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lstbOutputText.delete(0, lstbOutputText.length() - 1);
            lstbOutputText = null;
        }
    }

    public String tran_path(String pstrUserNO, String pstrPara,
                            String pstrServer, String pstrPortNO,
                            String pstrSysNO) {
        StringBuffer lstbPortNO = new StringBuffer();
        StringBuffer lstbSQL = new StringBuffer();
        Hashtable<String,Hashtable<String,Object>> lhtRunVersion = null;
        String lstrPrgLang = new String();
        String lstrPara = pstrPara;

        try {
            if (pstrPortNO != null && !pstrPortNO.trim().equals("")) {
                lstbPortNO.append(":");
                lstbPortNO.append(pstrPortNO);
            }

            lstbSQL.append(
                    "select runtime_version from wkf_ini_file where user_no='");
            lstbSQL.append(pstrUserNO);
            lstbSQL.append("'");

            lhtRunVersion = gqbnDAO.hashtableSQL(lstbSQL.toString());

            lstrPrgLang = (lhtRunVersion != null &&
                           ((Hashtable<String,Object>) lhtRunVersion.get("0")) != null ?
                           ((Hashtable<String,Object>) lhtRunVersion.get("0")).get(
                                   "RUNTIME_VERSION").toString() : "jsp");

            lstrPara = PublicFunction.replace(lstrPara, "{server}", pstrServer, true);

            lstrPara = PublicFunction.replace(lstrPara, "{sys}", pstrSysNO, true);

            lstrPara = PublicFunction.replace(lstrPara, "{port}", pstrPortNO, true);

            lstrPara = PublicFunction.replace(lstrPara, "{prg_lang}",
                                              lstrPrgLang, true);

            return (new StringBuffer("successfull")).append("/").append(
                    lstrPara).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return (new StringBuffer("fail")).append("/").append(e.toString()).
                    append("/").append("tran_path").toString();
        } finally {

        }
    }


}
